package ua.yandex.bank;

import java.util.concurrent.CopyOnWriteArrayList;

public class Bank {

    private final CopyOnWriteArrayList<Account> accounts;

    Bank() {
        accounts = new CopyOnWriteArrayList<>();
    }

    public Account create() {
        Account temp = new Account(accounts.size());
        synchronized (this) {
            accounts.add(temp);
        }
        return temp;
    }

    public int amountOfClients() {
        return accounts.size();
    }

    public int amountOfMoneyInAccount(int n) {
        if (n >= accounts.size()) {
            throw new MyException(" No created yet ");
        }
        return accounts.get(n).amountOfMoney.get();
    }

    public void withdraw(int number, int amount) {
        if (number >= accounts.size()) {
            throw new MyException(" No created yet ");
        }
        accounts.get(number).withdraw(amount);
    }

    public void deposit(int number, int amount) {
        if (number >= accounts.size()) {
            throw new MyException(" No created yet ");
        }
        accounts.get(number).deposit(amount);
    }

    public long amountOfMoneyInBank() {
        long result = 0;
        for (Account account : accounts) {
            result += account.amountOfMoney.get();
        }
        return result;
    }

    /*  public void writeBalances() {
     int i = 0;
     for (Account account : accounts) {
     System.out.println(i + "   " + account.amountOfMoney);
     i++;
     }
     }*/
    public void transfer(int fromNumber, int toNumber, int amount)
            throws InterruptedException {
        if (amount == 0) {
            return;
        }
        Account from = accounts.get(fromNumber);
        Account to = accounts.get(toNumber);
        if (from.withdraw(amount)) {
            to.deposit(amount);
        }
    }
}
